package com.seu.magicfilter.widget

import android.content.Context
import android.graphics.Bitmap
import android.util.AttributeSet
import android.util.Log
import com.seu.magicfilter.beautify.MagicJni
import com.seu.magicfilter.filter.base.gpuimage.GPUImageFilter
import com.seu.magicfilter.helper.SavePictureTask
import com.seu.magicfilter.utils.OpenGlUtils
import com.seu.magicfilter.widget.base.MagicBaseView
import java.nio.ByteBuffer
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10

class MagicImageView @JvmOverloads constructor(context: Context?, attrs: AttributeSet? = null) : MagicBaseView(context, attrs) {
    private val imageInput: GPUImageFilter
    private var _bitmapHandler: ByteBuffer? = null
    private var originBitmap: Bitmap? = null
    override fun onSurfaceCreated(gl: GL10, config: EGLConfig) {
        super.onSurfaceCreated(gl, config)
        imageInput.init()
    }

    override fun onSurfaceChanged(gl: GL10, width: Int, height: Int) {
        super.onSurfaceChanged(gl, width, height)
        adjustSize(0, false, false)
    }

    override fun onDrawFrame(gl: GL10) {
        super.onDrawFrame(gl)
        if (textureId == OpenGlUtils.NO_TEXTURE) textureId = OpenGlUtils.loadTexture(bitmap, OpenGlUtils.NO_TEXTURE)
        if (filter == null) imageInput.onDrawFrame(textureId, gLCubeBuffer, gLTextureBuffer) else filter.onDrawFrame(textureId, gLCubeBuffer, gLTextureBuffer)
    }

    override fun savePicture(savePictureTask: SavePictureTask) {}
    fun setImageBitmap(bitmap: Bitmap?) {
        if (bitmap == null || bitmap.isRecycled) return
        imageWidth = bitmap.width
        imageHeight = bitmap.height
        adjustSize(0, false, false)
        requestRender()
    }

    fun initMagicBeautify() {
        if (_bitmapHandler == null) {
            Log.e("MagicSDK", "please storeBitmap first!!")
            return
        }
        MagicJni.jniInitMagicBeautify(_bitmapHandler)
    }

    fun freeBitmap() {
        if (_bitmapHandler == null) return
        MagicJni.jniFreeBitmapData(_bitmapHandler)
        _bitmapHandler = null
    }

    var bitmap: Bitmap?
        get() = if (_bitmapHandler == null) null else MagicJni.jniGetBitmapFromStoredBitmapData(_bitmapHandler)
        set(bitmap) {
            if (_bitmapHandler != null) freeBitmap()
            _bitmapHandler = MagicJni.jniStoreBitmapData(bitmap)
            originBitmap = bitmap
        }

    init {
        imageInput = GPUImageFilter()
    }
}